<?php

use App\Models\Category;
use App\Models\User;
use App\Models\Topic;
use Illuminate\Support\Facades\Route;
use Illuminate\Support\Str;
use App\Models\Setting;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Arr;

if (!function_exists('route_class')) {

    function route_class()
    {
        return str_replace('.', '-', Route::currentRouteName());
    }
}


if (!function_exists('get_user_ids')) {

    function get_user_ids()
    {
        static $ids;
        if (!$ids) {
            $ids = User::with([])->pluck('id')->toArray();
        }
        return $ids;
    }
}


if (!function_exists('get_topic_ids')) {

    function get_topic_ids()
    {
        static $ids;
        if (!$ids) {
            $ids = Topic::with([])->pluck('id')->toArray();
        }
        return $ids;
    }
}

if (!function_exists('get_category_ids')) {

    function get_category_ids()
    {
        static $ids;
        if (!$ids) {
            $ids = Category::with([])->pluck('id')->toArray();
        }
        return $ids;
    }
}

if (!function_exists('get_categories')) {

    function get_categories()
    {
        $cache_key = 'topic_categories';
        $categories = Cache::get($cache_key);
        if (empty($categories)) {
            $categories = Category::all();
            Cache::put($cache_key, $categories);
        }

        return $categories;
    }
}

if (!function_exists('get_category_options')) {

    function get_category_options()
    {
        $cache_key = 'topic_category_options';
        $categories = Cache::get($cache_key);
        if (empty($categories)) {
            $categories = Category::with([])->pluck('name', 'id');
            Cache::put($cache_key, $categories);
        }

        return $categories;
    }
}

if (!function_exists('category_nav_active')) {

    function category_nav_active($category_id)
    {
        return active_class((if_route('categories.show') && if_route_param('category', $category_id)));
    }
}

if (!function_exists('make_excerpt')) {

    function make_excerpt($value, $length = 200)
    {
        $excerpt = trim(preg_replace('/\r\n|\r|\n+/', ' ', strip_tags($value)));
        return Str::limit($excerpt, $length);
    }
}

if (!function_exists('purifier_search_keywords')) {

    function purifier_search_keywords($keywords)
    {
        $keywords = clean($keywords, 'search_keywords');
        $keywords = strip_tags($keywords);
        $keywords = preg_replace('/\r\n|\r|\n|\'|\"+/', ' ', $keywords);

        return trim($keywords);
    }
}

if (!function_exists('get_active_users')) {

    function get_active_users()
    {
        return (new User())->getActiveUsers();
    }
}

if (!function_exists('get_links')) {

    function get_links()
    {
        return (new \App\Models\Link())->getAllCached();
    }
}

if (!function_exists('get_hot_topics')) {

    function get_hot_topics()
    {
        return (new \App\Models\Topic())->getHotTopicsCached();
    }
}

if (!function_exists('get_setting_types')) {

    function get_setting_types()
    {
        return [
            'switch' => '开关',
            'text' => '文本',
            'textarea' => '多行文本',
            'select' => '选择',
        ];
    }
}

if (!function_exists('get_setting_groups')) {

    function get_setting_groups()
    {
        return [
            'seo' => 'SEO',
            'site' => '站点',
            'env' => '环境',
            'develop' => '开发',
        ];
    }
}

if (!function_exists('get_settings')) {

    function get_settings($group = null)
    {
        $cache_key = 'site_settings' . ($group ? '_' . $group : '');
        $cache_expire_in_seconds = 60 * 60 * 24;

        return Cache::remember($cache_key, $cache_expire_in_seconds, function () use ($group) {
            $where = $group ? ['group' => $group] : [];
            return Setting::with([])->where($where)->get();
        });
    }
}

if (!function_exists('get_setting')) {

    function get_setting($variate, $default = null)
    {
        $cache_key = 'site_setting_' . $variate;
        return Cache::get($cache_key, $default);
    }
}

if (!function_exists('set_setting')) {

    function set_setting($variate, $value = null)
    {
        $cache_key = 'site_setting_' . $variate;
        Cache::put($cache_key, $value);
    }
}

if (!function_exists('set_env')) {

    function set_env($variate, $value = null)
    {
        $file = base_path() . '/.env';
        $variate = Str::upper($variate);
        $value = is_bool($value) ? ($value ? 'true' : 'false') : $value;
        try {
            $env_val = env($variate);
            $env_val = is_bool($env_val) ? ($env_val ? 'true' : 'false') : $env_val;
            $pattern = "/^{$variate}={$env_val}/m";
            $replacement = $variate . '=' . $value;

            file_put_contents($file, preg_replace(
                $pattern,
                $replacement,
                file_get_contents($file)
            ));
        } catch (Exception $exception) {

        }
    }
}

if (!function_exists('clear_settings')) {

    function clear_settings($group = null)
    {
        $cache_key = 'site_settings' . ($group ? '_' . $group : '');
        Cache::forget($cache_key);
    }
}

if (!function_exists('user_admin_config')) {

    function user_admin_config($key = null, $value = null)
    {
        $session = session();

        if (!$config = $session->get('admin.config')) {
            $config = config('admin');

            $config['lang'] = config('app.locale');
        }

        if (is_array($key)) {
            // 保存
            foreach ($key as $k => $v) {
                Arr::set($config, $k, $v);
            }

            $session->put('admin.config', $config);

            return;
        }

        if ($key === null) {
            return $config;
        }

        return Arr::get($config, $key, $value);
    }
}


if (!function_exists('get_tags')) {

    function get_tags()
    {
        static $tags;
        if (!$tags) {
            $tags = \App\Models\Tag::with([])
                ->orderByDesc('topic_count')
                ->orderBy('name')
                ->limit(20)
                ->get();
        }

        return $tags;
    }
}
